package com.xmwzw.catpu;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.view.View;

import com.mikepenz.fastadapter.FastAdapter;
import com.mikepenz.fastadapter.IAdapter;
import com.mikepenz.fastadapter.IItem;
import com.mikepenz.fastadapter.commons.adapters.FastItemAdapter;
import com.raizlabs.android.dbflow.sql.language.SQLite;
import com.xmwzw.catpu.bean.CollectionEvent;
import com.xmwzw.catpu.bean.SoftBean;
import com.xmwzw.catpu.databinding.ActivityCenterBinding;
import com.xmwzw.catpu.db.SoftModel;
import com.xmwzw.catpu.db.SoftModel_Table;
import com.xmwzw.catpu.http.BaseRequest;
import com.xmwzw.catpu.http.bean.BaseRespond;
import com.xmwzw.catpu.http.listener.LogoutListener;
import com.xmwzw.catpu.item.CollectItem;
import com.xmwzw.catpu.util.ActivityManagerUtils;
import com.xmwzw.catpu.util.CleanCacheUtils;
import com.xmwzw.catpu.util.Constant;
import com.xmwzw.catpu.util.SPFaceUtils;
import com.xmwzw.catpu.util.SystemUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;

/**
 * @author : wangzw
 * @date : 20-3-31上午9:44
 * @desc :
 */
public class MyCenterFragment extends BaseFragment {
    private ActivityCenterBinding centerBinding;
    private SimpleHandler handler;
    private FastItemAdapter fastItemAdapter = new FastItemAdapter();
    private List<CollectItem> items = new ArrayList<>();

    @Override
    public int getContentLayout() {
        return R.layout.activity_center;
    }

    @Override
    public void findViews(View view) {
        centerBinding = getBaseViewBinding();
        centerBinding.setClick(new OnClick());
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
        linearLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        centerBinding.rvCenter.setLayoutManager(linearLayoutManager);
        centerBinding.tvVersionname.setText("当前版本: " + SystemUtil.getVersionCode());
        centerBinding.setShow(!Constant.IS_NORMAL_LOGIN);
        setData();
        if (!EventBus.getDefault().hasSubscriberForEvent(CollectionEvent.class)) {
            EventBus.getDefault().register(this);
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void refresh(CollectionEvent event) {
        if (event != null) {
            items.clear();
            setData();
        }
    }


    private void setData() {
        List<SoftModel> softModels = SQLite.select().from(SoftModel.class).where(SoftModel_Table.isCollect.eq(true)).queryList();
        centerBinding.rvCenter.setVisibility(softModels.isEmpty() ? View.GONE : View.VISIBLE);
        for (int i = 0; i < softModels.size(); i++) {
            SoftBean softBean = new SoftBean();
            SoftModel softModel = softModels.get(i);
            softBean.name = softModel.name;
            softBean.version = softModel.version;
            softBean.icon_url = softModel.icon_url;
            softBean.down_url = softModel.down_url;
            items.add(new CollectItem().fillData(softBean));
        }
        fastItemAdapter.set(items);
        centerBinding.rvCenter.setAdapter(fastItemAdapter);

        centerBinding.rvCenter.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(getActivity(), MyCollectActivity.class));
            }
        });
        fastItemAdapter.withOnClickListener(new FastAdapter.OnClickListener() {
            @Override
            public boolean onClick(View v, IAdapter adapter, IItem item, int position) {
                startActivity(new Intent(getActivity(), MyCollectActivity.class));
                return false;
            }
        });
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        handler = new SimpleHandler(this);
        handler.sendEmptyMessageDelayed(1, 1500);
    }

    public class OnClick {

        public void cleanCache() {
            String formatSize = SystemUtil.getFormatSize(CleanCacheUtils.cleanApplicationData(true, BaseApplication.getInstance()));
            centerBinding.tvCache.setText(SystemUtil.getFormatSize(CleanCacheUtils.cleanApplicationData(false
                    , BaseApplication.getInstance())));
        }

        public void feedBack() {
            startActivity(new Intent(getActivity(), FeedBackActivity.class));
        }

        public void changePaw() {
            startActivity(new Intent(getActivity(), ChangePwdActivity.class));
        }

        public void goCollect() {
            startActivity(new Intent(getActivity(), MyCollectActivity.class));
        }

        public void logout() {
            showDialog();
        }
    }

    private void showDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        builder.setMessage("确认退出登录?")
                .setTitle("提示")
                .setPositiveButton("登录", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        dialogInterface.dismiss();
                        String username = SPFaceUtils.get(BaseApplication.getInstance(), Constant.KEY_LOGIN_NAME, "");
                        String token = SPFaceUtils.get(BaseApplication.getInstance(), Constant.KEY_LOGIN_TOKEN, "");
                        BaseRequest.getInstance().logout(username, token, new LogoutListener() {
                            @Override
                            public void getRespond(BaseRespond baseRespond) {
                                Message message = handler.obtainMessage();
                                message.what = 2;
                                message.obj = baseRespond;
                                handler.sendMessage(message);
                            }
                        });
                    }
                })
                .setNeutralButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        dialogInterface.dismiss();
                    }
                }).show();

    }

    private static class SimpleHandler extends Handler {
        private WeakReference<MyCenterFragment> weakReference;

        public SimpleHandler(MyCenterFragment fragment) {
            weakReference = new WeakReference<>(fragment);
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == 1) {
                String formatSize = SystemUtil.getFormatSize(CleanCacheUtils.cleanApplicationData(false, BaseApplication.getInstance()));
                weakReference.get().centerBinding.tvCache.setText(formatSize);
            } else if (msg.what == 2) {
                BaseRespond respond = (BaseRespond) msg.obj;
                if (respond.code == 0) {
                    SPFaceUtils.put(weakReference.get().getActivity(), Constant.KEY_LOGIN, false);
                    ActivityManagerUtils.getInstance().finishAllActivity();
                    weakReference.get().startActivity(new Intent(weakReference.get().getActivity(), LoginActivity.class));
                } else {
                    weakReference.get().showToast("退出登录失败");
                }

            }
        }
    }

}
